﻿using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

namespace Pibby.Controls
{
	public class SortableListView : EmptyListView
	{
		private ListViewColumnSorter _columnSorter;
		private ToolTip _toolTip;

		public SortableListView()
			: base()
		{
			_columnSorter = new ListViewColumnSorter();
			this.ListViewItemSorter = _columnSorter;
			this.Sorting = SortOrder.Descending;

			this.ColumnClick += new ColumnClickEventHandler(SortableListView_ColumnClick);
			this.ShowItemToolTips = true;
			this._toolTip = new ToolTip ();
		}

		protected void ShowTooltip(string text, Point location)
		{
			this._toolTip.Show(text, this, location, 2000);
		}

		void SortableListView_ColumnClick(object sender, ColumnClickEventArgs e)
		{
			// Determine if clicked column is already the column that is being sorted.
			if (e.Column == _columnSorter.SortColumn)
			{
				// Reverse the current sort direction for this column.
				if (_columnSorter.Order == SortOrder.Ascending)
				{
					_columnSorter.Order = SortOrder.Descending;
				}
				else
				{
					_columnSorter.Order = SortOrder.Ascending;
				}
			}
			else
			{
				// Set the column number that is to be sorted; default to ascending.
				_columnSorter.SortColumn = e.Column;
				_columnSorter.Order = SortOrder.Ascending;
			}

			this.Sort();
		}

		public void SortByColumn(int index, SortOrder sort)
		{
			if (index < this.Columns.Count)
			{
				_columnSorter.SortColumn = index;
				_columnSorter.Order = sort;

				this.Sort();
			}
		}

		protected void SuspendSorting()
		{
			this.ListViewItemSorter = null;
		}

		protected void RestoreSorting()
		{
			if (this._columnSorter == null)
			{
				this._columnSorter = new ListViewColumnSorter();
			}

			this.ListViewItemSorter = _columnSorter;
		}

		protected void UpdateContent(IEnumerable<ListViewItem> items)
		{
			this.BeginUpdate();
			this.SuspendSorting();
			this.Items.Clear();

			//int index = 0;
			//Color lightestGray = Color.FromArgb(0xee, 0xee, 0xee);
			foreach (ListViewItem item in items)
			{
				//item.BackColor = (++index % 2 == 0) ? lightestGray : Color.White;
				this.Items.Add(item);
			}

			this.AutoSizeColumns();
			this.RestoreSorting();
			this.EndUpdate();
		}
	}
}
